#-*- coding: utf-8 -*-

import requests
import re
import time
import hashlib
import base64
import struct
import pyaudio
import wave
import sys;sys.path.append('../')
import Config as C


URL = "http://api.xfyun.cn/v1/service/v1/tts"
AUE = "raw"
APPID = C.sS_APPID
API_KEY = C.sS_API_KEY

def getHeader():
        #param = "{\"aue\":\""+AUE+"\",\"auf\":\"audio/L16;rate=16000\",\"voice_name\":\"xiaoyan\",\"engine_type\":\"x\"}"
        param = '{"aue":"raw","auf":"audio/L16;rate=16000","voice_name":"xiaoyan","engine_type":"aisound"}'
        paramBase64 = base64.b64encode(param)
        m2 = hashlib.md5()
        curTime = str(int(time.time()))
        m2.update(API_KEY + curTime + paramBase64)
        checkSum = m2.hexdigest()
        header ={
                'X-CurTime':curTime,
                'X-Param':paramBase64,
                'X-Appid':APPID,
                'X-CheckSum':checkSum,
                'X-Real-Ip':'127.0.0.1',
                'Content-Type':'application/x-www-form-urlencoded; charset=utf-8',
        }
        return header

def getBody(text):
        data = {'text':text}
        return data

def writeFile(file, content):
    with open(file, 'wb') as f:
        f.write(content)
    f.close()


def synthesisInfo(msg):
        r = requests.post(URL,headers=getHeader(),data=getBody(msg))
        contentType = r.headers['Content-Type']
        if contentType == "audio/mpeg":
            sid = r.headers['sid']
            if AUE == "raw":
                #writeFile("audio/"+"hello.wav", r.content)
                writeFile("hello.wav", r.content)
            else :
                writeFile("audio/"+sid+".mp3", r.content)
            print "success, sid = " + sid
        else :
            print r.text


def voiceBroadcast(filename):
        chunk = 1024                    #define stream chunk
        f = wave.open(filename,"rb")    #open a wav format music
        p = pyaudio.PyAudio()           #instantiate PyAudio
        #open stream
        stream = p.open(
                format = p.get_format_from_width(f.getsampwidth()),
                channels = f.getnchannels(),
                rate = f.getframerate(),
                output = True
        )
        data = f.readframes(chunk)  #read data
        #paly stream
        while data != '':
            stream.write(data)
            data = f.readframes(chunk)
        stream.stop_stream()    #stop stream
        stream.close()
        p.terminate() 

#synthesisInfo('板栗板栗，现炒现卖')
#voiceBroadcast('hello.wav')
